//
//  FeedbackViewController.m
//  suRead
//
//  Created by bao on 15/9/12.
//  Copyright (c) 2015年 bao. All rights reserved.
//

#import "FeedbackViewController.h"
#import "VPImageCropperViewController.h"
#import "DynamicScrollView.h"
#import "ServiceUtils.h"

@interface FeedbackViewController ()<UITextViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,VPImageCropperDelegate,deleteDelegate,UITextFieldDelegate>
{
    UITextView *textview;
    
    NSInteger clicked;
    
    NSMutableArray *images;
    DynamicScrollView *dynamicScrollView;
    UIButton * addphoto;
    NSMutableArray * imgs;
    int index;
  
}

@end

@implementation FeedbackViewController
@synthesize titlestring;

- (void)backAction:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)NavInit{
    
    UIView * view = [[UIView alloc]initWithFrame:NSRect(0, 0, SCREEN_WIDTH, 64)];
    view.backgroundColor  = Maincolors;
    [self.view addSubview:view];
    
     [theAppDelegate settitle:self.view title:titlestring];
    
    UIButton *backbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backbtn setFrame:CGRectMake(7, 28, 60/2, 50/2)];
    [backbtn setImage:[UIImage imageNamed:@"night_icon_back.png"] forState:UIControlStateNormal];
    [backbtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backbtn];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    images = [[NSMutableArray alloc]initWithCapacity:0];
    
    [self NavInit];
    [self UIView];
 
    self.view.backgroundColor = WithRed(239.0, 239.0, 243.0, 1.0);
}

-(void)UIView{
    
    UITextField * titlefield = [[UITextField alloc] initWithFrame:CGRectMake(0, 80, SCREEN_WIDTH, 40)];
    [titlefield setBorderStyle:UITextBorderStyleNone]; //外框类型
    titlefield.placeholder = @" 请填写标题"; //默认显示的字
    [titlefield setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"];
    titlefield.returnKeyType = UIReturnKeyDone;
    titlefield.tag = 10;
    titlefield.textAlignment = NSTextAlignmentLeft;
    titlefield.backgroundColor  =[UIColor whiteColor];
    titlefield.delegate = self;
    [self.view addSubview:titlefield];
    
    
    //初始化并定义大小
    textview = [[UITextView alloc] initWithFrame:CGRectMake(0, 130, SCREEN_WIDTH, 140)];
    textview.backgroundColor=[UIColor whiteColor]; //背景色
    textview.scrollEnabled = NO;    //当文字超过视图的边框时是否允许滑动，默认为“YES”
    textview.editable = YES;        //是否允许编辑内容，默认为“YES”
    textview.delegate = self;       //设置代理方法的实现类
    textview.font=[UIFont fontWithName:@"Arial" size:16.0]; //设置字体名字和字体大小;
    textview.returnKeyType = UIReturnKeyDone;//return键的类型
    textview.keyboardType = UIKeyboardTypeDefault;//键盘类型
    textview.textAlignment = NSTextAlignmentLeft; //文本显示的位置默认为居左
    textview.dataDetectorTypes = UIDataDetectorTypeAll; //显示数据类型的连接模式（如电话号码、网址、地址等）
    textview.textColor = [UIColor grayColor];
    textview.text = @"请输入报料内容";//设置显示的文本内容
    [self.view addSubview:textview];
    
    dynamicScrollView = [[DynamicScrollView alloc] initWithFrame:CGRectMake(5, textview.frame.origin.y+textview.frame.size.height+10, SCREEN_WIDTH-10, (SCREEN_WIDTH-10)/4-5) withImages:[images mutableCopy]];
    dynamicScrollView.delegate = self;
    [self.view addSubview:dynamicScrollView];

    
    
    addphoto = [UIButton buttonWithType:UIButtonTypeCustom];
    addphoto.frame = CGRectMake(0, 0, (SCREEN_WIDTH-20)/4-5, dynamicScrollView.scrollView.frame.size.height);
    [addphoto setImage:[UIImage imageNamed:@"photoadd.png"] forState:UIControlStateNormal];
    [addphoto addTarget:self action:@selector(UesrImageClicked:) forControlEvents:UIControlEventTouchUpInside];
    [dynamicScrollView.scrollView addSubview:addphoto];
    
    
    UITextField * textField = [[UITextField alloc] initWithFrame:CGRectMake(0, textview.frame.origin.y+textview.frame.size.height+(SCREEN_WIDTH-20)/4+15, SCREEN_WIDTH, 40)];
    [textField setBorderStyle:UITextBorderStyleNone]; //外框类型
    textField.placeholder = @" 请填写您的联系方式(手机号码)"; //默认显示的字
    [textField setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"];
    textField.returnKeyType = UIReturnKeyDone;
    textField.tag = 11;
    textField.textAlignment = NSTextAlignmentLeft;
    textField.backgroundColor  =[UIColor whiteColor];
    textField.delegate = self;
    [self.view addSubview:textField];
    
    UIButton * Send = [UIButton buttonWithType:UIButtonTypeCustom];
    Send.frame = CGRectMake(0, textview.frame.origin.y+textview.frame.size.height+(SCREEN_WIDTH-20)/4+80, SCREEN_WIDTH,44);
    [Send setBackgroundImage:[theAppDelegate createImageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    [Send addTarget:self action:@selector(onSend) forControlEvents:UIControlEventTouchUpInside];
    [Send setTitle:@"发送" forState:UIControlStateNormal];
    [Send setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [Send setTitleColor:Maincolors forState:UIControlStateHighlighted];
    Send.layer.cornerRadius = 3.5;
    Send.layer.masksToBounds = YES;
    [self.view addSubview:Send];
    
}

-(void)UesrImageClicked:(NSInteger)clicked{
    
    UIActionSheet *sheet;
    
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        sheet  = [[UIActionSheet alloc] initWithTitle:@"选择图像" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"拍照", @"从相册选择", nil];
    }
    else {
        sheet = [[UIActionSheet alloc] initWithTitle:@"选择图像" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"从相册选择", nil];
    }
    
    sheet.tag = 255;
    
    [sheet showInView:self.view];
    
}


#pragma mark - action sheet delegte
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 255) {
        NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            switch (buttonIndex) {
                case 0:
                    return;
                case 1: //相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                case 2: //相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
            }
        }
        else {
            if (buttonIndex == 0) {
                return;
            } else {
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }
        }
         //跳转到相机或相册页面
        UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
       
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = sourceType;
         imagePickerController.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
        [self presentViewController:imagePickerController animated:YES completion:^{
            [imagePickerController setDelegate:self];
            
        }];
        
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    DebugLog(@"imagePickerController");

    
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [self imageByScalingToMaxSize:portraitImg];
        // 裁剪
        VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, self.view.frame.size.width, self.view.frame.size.width) limitScaleRatio:3.0];
        imgEditorVC.delegate = self;
        [self presentViewController:imgEditorVC animated:YES completion:^{
            // TO DO
        }];
    }];

}

-(void)updateImage:(NSMutableArray *)arr{
    
    if([arr count]>3){
        
        addphoto.hidden = YES;
    }else{
        addphoto.hidden  =NO;
    }
    addphoto.frame = CGRectMake([arr count]*(SCREEN_WIDTH-15)/4, 0, (SCREEN_WIDTH-20)/4-5, dynamicScrollView.scrollView.frame.size.height);
    
}

#pragma mark VPImageCropperDelegate
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    //     theImage = [self imageWithImageSimple:editedImage scaledToSize:CGSizeMake(500, 500)];
    DebugLog(@"editedImage = %f  %f",editedImage.size.width,editedImage.size.height);
    [images addObject:editedImage];
    
    [dynamicScrollView addImageView:editedImage];
    
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        DebugLog(@"上传");
        
        [self updateImage:dynamicScrollView.imageViews];
        
        
    }];
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
         DebugLog(@"imageCropperDidCancel");
        [self dismissViewControllerAnimated:YES completion:nil];
    }];

}


#pragma mark image scale utility
-(UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < SCREEN_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = SCREEN_WIDTH;
        btWidth = sourceImage.size.width * (SCREEN_WIDTH / sourceImage.size.height);
    } else {
        btWidth = SCREEN_WIDTH;
        btHeight = sourceImage.size.height * (SCREEN_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}


-(UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

// 当用户取消时，调用该方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    DebugLog(@"imagePickerControllerDidCancel");
    [picker dismissViewControllerAnimated:YES completion:nil];
}



//压缩图片
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}



//将要开始编辑
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    if([textview.text isEqualToString:@"请输入报料内容"]){
     
        textview.text  =@"";
    }
    return YES;
}

//控制输入文字的长度和内容，可通调用以下代理方法实现
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
//    if (range.location>=10)
//    {
//        //控制输入文本的长度
//        return  NO;
//    }
    if ([text isEqualToString:@"\n"]) {
        //禁止输入换行
        [textView resignFirstResponder];
        return NO;
    }
    else
    {
        return YES;
    }
}


#pragma mark ---------------- 键盘代理 -------------------
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
    UITextField * tf2 = (UITextField*)[self.view viewWithTag:11];
    
    if(textField == tf2){
        int Height;
        if(iPhone4){
            Height = 180;
        }else{
            Height = 85;
        }
        [theAppDelegate viewKeyboardAppearChangeRect:Height View:self.view];
    }
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    UITextField * tf2 = (UITextField*)[self.view viewWithTag:11];
    
    if(textField == tf2){
        
        [theAppDelegate viewKeyboardDisappearChangeRect:self.view];
    }
    
    [textField resignFirstResponder];
    
    
    return YES;
}


/**
 *  发送
 */

-(void)onSend{
    
//    DebugLog(@"images =  %@",dynamicScrollView.imageViews);

//    
    UITextField * tf_title = (UITextField*)[self.view viewWithTag:10];
    UITextField * tf_phone = (UITextField*)[self.view viewWithTag:11];
    
    if([tf_title.text isEqualToString:@""]){
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"标题不能为空" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
    if([textview.text isEqualToString:@""]){
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"报料内容不能为空" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
    if(tf_phone.text.length!=11){
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"手机号码不能为空" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
    
    
    imgs = [[NSMutableArray alloc]initWithCapacity:0];
    index  = 0;
    UIImageView * img = [dynamicScrollView.imageViews objectAtIndex:index];
    [self uploadImage:img.image Current:index];
    
    
    
}


//
#pragma mark - 文件上传
- (void)uploadImage:(UIImage*)image Current:(int)current
{
    [theAppDelegate showWithStatus:self.view Label:@"图片上传中..."];
    
    [[ServiceUtils commonHTTPManager] POST:url_net_imgfile parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
    {
        
        NSData *imageData=UIImageJPEGRepresentation(image,100);
        [formData appendPartWithFileData:imageData name:@"imgfile" fileName:@"image.jpg" mimeType:@"image/jpeg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (responseObject == nil) {
            DebugLog(@"json parse failed \r\n");
            return;
        }
        
        if([[responseObject objectForKey:@"success"] intValue] ==0){
            
            [theAppDelegate alert:[responseObject objectForKey:@"msg"]];
            return;
            
        }else{
            
            
            index+=1;
            
            DebugLog(@"index  ================  %d",index);
            
            
            [imgs addObject:[responseObject objectForKey:@"imgurl"]];
            
            if(current == [dynamicScrollView.imageViews count]-1){
                
                
                NSString * string = [[NSString alloc]init];
                for(NSString * name in imgs){
                    
                    string = [string stringByAppendingFormat:@"%@;",name];
                    
                }
                
                NSString *temp = [string substringToIndex:[string length]-1];
                
                DebugLog(@"上传完成  ===================  %d     %@     string = %@",current,[json objectForKey:@"imgurl"],temp);
                
                [self Baoliao:temp];
                [theAppDelegate showWithStatus:self.view Label:@"提交报料中..."];
                
                
            }else{
                
                DebugLog(@"上传中  ====================  %d",current);
                
                
                UIImageView * img = [dynamicScrollView.imageViews objectAtIndex:index];
                [self uploadImage:img.image Current:index];
                
                
            }
            
            
        }

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DebugLog(@"Error: %@", error);
        [theAppDelegate dismiss];
    }];
    
}



/**
 *  报料
 */

- (void)Baoliao:(NSString*)imgaes
{
    NSString * username;
    
    if(![checkNull([[NSUserDefaults standardUserDefaults] valueForKey:@"user_data"]) isEqualToString:@""]){
        
        username = [[[NSUserDefaults standardUserDefaults] valueForKey:@"user_data"] objectForKey:@"username"];
    }else{
        
        username = @"";
    }

    UITextField * tf_title = (UITextField*)[self.view viewWithTag:10];
    UITextField * tf_tel = (UITextField*)[self.view viewWithTag:11];
    
    NSDictionary *dict = @{@"title": tf_title.text,@"content": textview.text,@"imgs":imgaes,@"contact":tf_tel.text,@"username":username};
    DebugLog(@"dict =  %@", dict);
    
    [[ServiceUtils commonHTTPManager] POST:url_net_baoliao parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject == nil) {
            DebugLog(@"json parse failed \r\n");
            return;
        }
        
        if([[responseObject objectForKey:@"success"] intValue] ==0){
            
            [theAppDelegate alert:[responseObject objectForKey:@"msg"]];
            return;
            
        }else{
            
            [theAppDelegate alert:@"报料成功"];
            
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DebugLog(@"Error: %@", error);
        [theAppDelegate dismiss];
    }];
    
}

@end
